package com.hyjiacan.apps.audionly.data.repository

import android.os.Environment
import com.hyjiacan.apps.audionly.data.model.VideoFile
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
import java.util.UUID
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.extension.ExtendWith
import io.mockk.junit5.MockKExtension
import io.mockk.mockk
import org.junit.jupiter.api.BeforeEach

/**
 * FileRepositoryImpl类的单元测试
 */
@ExtendWith(MockKExtension::class)
class FileRepositoryImplTest {
    private val repository = FileRepositoryImpl()

    private lateinit var environment: Environment

    @BeforeEach
    fun setup() {
        environment = mockk<Environment>(relaxed = true)
    }

    @Test
    fun `test getRootDirectory`() {
        // 测试获取根目录
        val rootDir = repository.getRootDirectory()
        assertNotNull(rootDir)
        assertFalse(rootDir.isEmpty())
    }

    @Test
    fun `test fileExists`() {
        // 测试文件存在
        val tempFile = File.createTempFile("test", ".mp4")
        assertTrue(repository.fileExists(tempFile.absolutePath))

        // 测试文件不存在
        assertFalse(repository.fileExists("/non/existent/file.mp4"))

        // 清理临时文件
        tempFile.delete()
    }

    @Test
    fun `test getVideoFiles with valid directory`() = runBlocking {
        // 创建临时目录
        val tempDir = File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString())
        tempDir.mkdirs()

        // 创建测试文件
        File(tempDir, "video1.mp4").createNewFile()
        File(tempDir, "video2.mkv").createNewFile()
        File(tempDir, "audio.mp3").createNewFile() // 非视频文件

        // 测试获取视频文件
        val videoFiles = repository.getVideoFiles(tempDir.absolutePath)

        // 验证结果
        assertEquals(2, videoFiles.size)
        assertTrue(videoFiles.any { it.name == "video1.mp4" })
        assertTrue(videoFiles.any { it.name == "video2.mkv" })
        assertFalse(videoFiles.any { it.name == "audio.mp3" })

        // 清理临时目录
        tempDir.deleteRecursively()
    }

    @Test
    fun `test getVideoFiles with invalid directory`() = runBlocking {
        // 测试无效目录
        val videoFiles = repository.getVideoFiles("/non/existent/directory")
        assertTrue(videoFiles.isEmpty())
    }
}